//
//  ViewController.swift
//  StoreSearch
//
//  Created by cygarm on 15/12/21.
//  Copyright © 2015年 cygarm. All rights reserved.
//

import UIKit

enum SearchResultSource {
	case WEB
	case FILE
}
var kSearchResultSource = SearchResultSource.FILE

class SearchViewController: UIViewController {

	@IBOutlet weak var tableView: UITableView!
	@IBOutlet weak var searchBar: UISearchBar!
	@IBOutlet weak var segmentedControl: UISegmentedControl!
	
	struct TableViewCellIdentifiers {
		static let searchResultCell = "SearchResultCell"
		static let nothingFoundCell = "NothingFoundCell"
		static let loadingCell = "LoadingCell"
	}
	
	let search = Search()
	var landscapeViewController: LandscapeViewController?
	weak var splitViewDetail: DetailViewController?
	
	//MARK: - Lifecycle
	required init?(coder aDecoder: NSCoder) {
		super.init(coder: aDecoder)
		
		NSNotificationCenter.defaultCenter().addObserverForName(UIContentSizeCategoryDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
			print("UIContentSizeCategoryDidChangeNotification")
			self.tableView.reloadData()
		}
	}
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		title = NSLocalizedString("Search", comment: "Split-view master button")
		
		if UIDevice.currentDevice().userInterfaceIdiom != .Pad {
			searchBar.becomeFirstResponder()
		}
		
		tableView.contentInset = UIEdgeInsets(top: 64/*search bar*/+44/*segmented control's navigation bar*/, left: 0, bottom: 0, right: 0)
		tableView.estimatedRowHeight = 80
		tableView.rowHeight = UITableViewAutomaticDimension
				
		var cellNib = UINib(nibName: TableViewCellIdentifiers.searchResultCell, bundle: nil)
		tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.searchResultCell)
		cellNib = UINib(nibName: TableViewCellIdentifiers.nothingFoundCell, bundle: nil)
		tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.nothingFoundCell)
		cellNib = UINib(nibName: TableViewCellIdentifiers.loadingCell, bundle: nil)
		tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.loadingCell)
	}
	
	override func viewDidDisappear(animated: Bool) {
		super.viewDidDisappear(animated)
		
		NSNotificationCenter.defaultCenter().removeObserver(self)
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
	
	override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
		super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
		
		let rect = UIScreen.mainScreen().bounds
		// iPhone6s Plus = (736*414) points
		if (rect.width == 736 && rect.height == 414) || // portrait
			 (rect.width == 414 && rect.height == 736) { // landscape
			if presentedViewController != nil {
				dismissViewControllerAnimated(true, completion: nil)
			}
		} else if UIDevice.currentDevice().userInterfaceIdiom != .Pad {
			switch newCollection.verticalSizeClass {
			case .Compact:
				showLandscapeViewWithCoordinator(coordinator)
			case .Regular, .Unspecified:
				hideLandscapeViewWithCoordinator(coordinator)
			}
		}
	}

	override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
		if segue.identifier == "ShowDetail" {
			switch search.state {
			case .Results(let list):
				let detailViewController = segue.destinationViewController as! DetailViewController
				let indexPath = sender as! NSIndexPath
				let searchResult = list[indexPath.row]
				detailViewController.searchResult = searchResult
				detailViewController.isPopUp = true
			default:
				break
			}
		}
	}
}

//MARK: - helper method - UI handle
extension SearchViewController {
	func hideMasterPane() {
		UIView.animateWithDuration(0.25, animations: { () -> Void in
			self.splitViewController!.preferredDisplayMode = .PrimaryHidden
		}) { (_) -> Void in
			self.splitViewController!.preferredDisplayMode = .Automatic
		}
	}
}

//MARK: - helper method - Landscape view
extension SearchViewController {
	func showLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator) {
		precondition(landscapeViewController == nil)
		
		landscapeViewController = storyboard!.instantiateViewControllerWithIdentifier("LandscapeViewController") as? LandscapeViewController
		if let controller = landscapeViewController {
			controller.search = search
			
			controller.view.frame = view.bounds
			controller.view.alpha = 0
			
			view.addSubview(controller.view)
			addChildViewController(controller)
			
			coordinator.animateAlongsideTransition({ (_) -> Void in
				controller.view.alpha = 1
				self.searchBar.resignFirstResponder()
				if self.presentationController != nil {
					self.dismissViewControllerAnimated(true, completion: nil)
				}
			}, completion: { (_) -> Void in
					controller.didMoveToParentViewController(self)
			})
		}
	}
	
	func hideLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator) {
		if let controller = landscapeViewController {
			controller.willMoveToParentViewController(nil)
			
			coordinator.animateAlongsideTransition({ (_) -> Void in
				controller.view.alpha = 0
				}, completion: { (_) -> Void in
					controller.view.removeFromSuperview()
					controller.removeFromParentViewController()
					self.landscapeViewController = nil
			})
		}
		if self.presentedViewController != nil {
			self.dismissViewControllerAnimated(true, completion: nil)
		}
	}
}

//MARK: - helper method - URL handle
extension SearchViewController {	
	func showNetworkError() {
		let alert = UIAlertController(title: "Whoops...", message: "There was an error reading from the iTunes Store.Please try again.", preferredStyle: .Alert)
		let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
		alert.addAction(action)
		
		presentViewController(alert, animated: true, completion: nil)
	}
}

//MARK: - IBAction
extension SearchViewController {
	@IBAction func segmentChanged(sender: AnyObject) {
		print("Segment changed: \(sender.selectedSegmentIndex)")
		performSearch()
	}
	
}

//MARK: - UISearchBarDelegate
extension SearchViewController: UISearchBarDelegate {
	func searchBarSearchButtonClicked(searchBar: UISearchBar) {
		performSearch()
	}
	
	func performSearch() {
		if let category = Search.Category(rawValue: segmentedControl.selectedSegmentIndex) {
			search.performSearchForText(searchBar.text!, category: category) { (success) -> Void in
				if !success {
					self.showNetworkError()
				}
				self.tableView.reloadData()
			}
			tableView.reloadData()
			searchBar.resignFirstResponder()
		}
		
		if let controller = self.landscapeViewController {
			controller.searchResultsReceived()
		}
	}
	
	func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
		return .TopAttached
	}
}

//MARK: - UITableViewDataSource
extension SearchViewController: UITableViewDataSource {
	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		switch search.state {
		case .NotSearchedYet:
			return 0
		case .Loading:
			return 1
		case .NoResults:
			return 1
		case .Results(let list):
			return list.count
		}
	}
		
	func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		switch search.state {
		case .NotSearchedYet:
			fatalError("Should never get here")
		case .Loading:
			let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.loadingCell, forIndexPath: indexPath) as UITableViewCell
			let spinner = cell.viewWithTag(100) as! UIActivityIndicatorView
			spinner.startAnimating()
			
			return cell
		case .NoResults:
			return tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as UITableViewCell
		case .Results(let list):
			let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.searchResultCell, forIndexPath: indexPath) as! SearchResultCell
			let searchResult = list[indexPath.row]
			cell.configureForSearchResult(searchResult)
			
			return cell
		}
	}
}

//MARK: - UITableViewDelegate
extension SearchViewController: UITableViewDelegate {
	func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
		searchBar.resignFirstResponder()
		
		if view.window!.rootViewController!.traitCollection.horizontalSizeClass == .Compact {
			tableView.deselectRowAtIndexPath(indexPath, animated: true)
			performSegueWithIdentifier("ShowDetail", sender: indexPath)
		} else {
			switch search.state {
			case .Results(let list):
				splitViewDetail?.searchResult = list[indexPath.row]
			default:
				break
			}
			
			if splitViewController!.displayMode != .AllVisible {
				hideMasterPane()
			}
		}
	}
	
	func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
		switch search.state {
		case .NotSearchedYet, .Loading, .NoResults:
			return nil
		case .Results:
			return indexPath
		}
	}
}
